﻿
namespace EasyNet.Solr.Impl
{
    using System.Linq;
    using System.Xml.Linq;

    /// <summary>
    /// xml格式返回数据头解析器
    /// </summary>
    public class XmlResponseHeaderParser : ISolrResponseParser<string, ResponseHeader>
    {
        public ResponseHeader Parse(string result)
        {
            if (result == null)
            {
                return null;
            }

            var xmlDoc = XDocument.Parse(result);

            var responseHeader = from e in xmlDoc.Root.Elements("lst")
                                 where (string)e.Attribute("name") == "responseHeader"
                                 select e;

            if (responseHeader == null)
            {
                return null;
            }

            return new ResponseHeader()
            {
                Status = (from e in responseHeader.Elements("int")
                          where (string)e.Attribute("name") == "status"
                          select int.Parse(e.Value)).Single<int>(),
                QTime = (from e in responseHeader.Elements("int")
                         where (string)e.Attribute("name") == "QTime"
                         select int.Parse(e.Value)).Single<int>()
            };
        }
    }
}
